package com.hxs.colorfultest2.controller;

import com.hxs.colorfultest2.dao.UserDao;
import com.hxs.colorfultest2.domain.User;
import com.hxs.colorfultest2.model.ResponseModel;
import com.hxs.colorfultest2.service.UserService;
import com.sun.org.apache.xpath.internal.operations.Mod;
import org.apache.tomcat.util.codec.binary.Base64;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import sun.misc.BASE64Decoder;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.Response;
import java.io.*;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@Controller
public class UserManagerController {

    @Autowired
    UserService userService;

    /*添加用户*/
    @RequestMapping(value = "/addU", method = RequestMethod.GET)
    public void addUser(HttpServletRequest request, HttpServletResponse response) throws IOException {


        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String[] permission = request.getParameter("checkValue").split(",");
        System.out.println("新增的用户数据为" + username + " " + password);
        String picPath = "D:" + File.separator + "uploadImg" + File.separator + "colorful.jpg";
        User user = new User();

        if (permission == null) {
            user.setManagerFlag("");
        } else {
            String add = " ", delete = " ", download = " ", search = " ";
            for (int i = 0; i < permission.length; i++) {
                if ("add".equals(permission[i])) {
                    add = "上传,";
                }
                if ("delete".equals(permission[i])) {
                    delete = "删除,";
                }
                if ("download".equals(permission[i])) {
                    download = "下载,";
                }
                if ("search".equals(permission[i])) {
                    search = "查看,";
                }
            }
            user.setManagerFlag((add + delete + download + search).replace(" ", ""));
        }
        user.setUsername(username);
        user.setPassword(password);
        user.setRole_id(2);
        user.setHeadpic(picPath);
        userService.addUser(user);

        response.getOutputStream().print("1");
    }

    /*获取所有用户进行分页*/
    @RequestMapping("/user")
    public Model getAllUser(Model model, @RequestParam(value = "curPage", required = false) Integer curPage) {
        int pageSize = 10;

        /*当前页*/
        if (curPage == null) {
            curPage = 1;
        }
        int totalRows = userService.getUserByTotal();
        int totalPages = totalRows / pageSize;
        int left = totalRows % pageSize;
        if (left > 0) {
            totalPages = totalPages + 1;
        }

        Map<String, Object> paramMap = new ConcurrentHashMap<>();
        /*计算当前页*/
        int start = (curPage - 1) * pageSize;
        paramMap.put("start", start);
        paramMap.put("pageSize", pageSize);

        List<User> userList = userService.getUserByPage(paramMap);

        for(User user:userList){
            user.setManagerFlag(user.getManagerFlag().replaceAll(","," "));
        }
        model.addAttribute("userList", userList);
        model.addAttribute("totalRows", totalRows);
        model.addAttribute("curPage", curPage);
        model.addAttribute("totalPages", totalPages);
        model.addAttribute("pageSize", pageSize);

        for (User user : userList) {
            System.out.println(user);
        }

        return model;
    }

    /*用户姓名查重*/
    @RequestMapping(value = "/nameCheck", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public void nameCheck(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String name = request.getParameter("name");
        boolean b = userService.checkName(name);
        System.out.println("输入框的用户名为" + name + " " + b);

        // response.getWriter().write("{\"data\":"+b+"}");*/
        String resultString;
        if (b) {
            resultString = "1";
        } else {
            resultString = "0";
        }

        response.getOutputStream().print(resultString);

    }

    /*删除用户*/
    @RequestMapping(value = "/deleteU{username}", method = RequestMethod.GET)
    public String deleteU(@PathVariable("username") String username) throws IOException {
        System.out.println("要删除的用户名为" + " " + username);
        userService.deleteUser(username);
        return "redirect:/user";


    }

    /*获取更新用户用户和权限*/
    @RequestMapping(value = "/updateU{username}", method = RequestMethod.GET)
    public String updateU(@PathVariable("username") String username, Model model) throws IOException {
        System.out.println("要更新的用户名为" + " " + username);
        User user = userService.getUserByName(username);
        //      System.out.println("要更新的用户" + " " + user);
        model.addAttribute("updateUser", user);
        String[] permission = user.getManagerFlag().split(",");

        String addstr = " ", deletestr = " ", downloadstr = " ", searchstr = " ";
        int add = 5, delete = 5, download = 5, search = 5;
        if (permission != null) {
            for (int i = 0; i < permission.length; i++) {
                System.out.println("当前用户" + " " + permission[i]);
                if ("上传".equals(permission[i])) {
                    addstr = "add";
                    add = i;
                }
                if ("删除".equals(permission[i])) {
                    deletestr = "delete";
                    delete = i;
                }
                if ("下载".equals(permission[i])) {
                    downloadstr = "download";
                    download = i;
                }
                if ("查看".equals(permission[i])) {
                    searchstr = "search";
                    search = i;
                }
            }
            if (add < 4) {
                model.addAttribute("addstr", "add");
                System.out.println("当前用户权限" + " " + permission[add]);
            }

            if (delete < 4) {
                model.addAttribute("deletestr", "delete");
                System.out.println("当前用户权限" + " " + permission[delete]);
            }
            if (download < 4) {
                model.addAttribute("downloadstr", "download");
                System.out.println("当前用户权限" + " " + permission[download]);
            }
            if (search < 4) {
                model.addAttribute("searchstr", "search");
                System.out.println("当前用户权限" + " " + permission[search]);
            }

        } else {
            model.addAttribute("addstr", null);
            model.addAttribute("searchstr", null);
            model.addAttribute("downloadstr", null);
            model.addAttribute("deletestr", null);

        }

        System.out.println("经过装换后权限为" + addstr + " " + deletestr + " " + downloadstr + " " + searchstr);
        return "updateUser";

    }


    /*保存更新后的用户*/
    @RequestMapping(value = "/saveU", method = RequestMethod.GET)
    public void saveU(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String[] permission = request.getParameter("checkValue").split(",");
        //   System.out.println("当前用户申请的权限为" + " " + permission.toString());
        String username = request.getParameter("username");
        //    System.out.println("要更新的用户名为" + " " + username);
        User user = userService.getUserByName(username);

        /*判断用户权限*/
        if (permission == null) {
            user.setManagerFlag("");
        } else {
            String add = " ", delete = " ", download = " ", search = " ";
            for (int i = 0; i < permission.length; i++) {
                if ("add".equals(permission[i])) {
                    add = "上传,";
                }
                if ("delete".equals(permission[i])) {
                    delete = "删除,";
                }
                if ("download".equals(permission[i])) {
                    download = "下载,";
                }
                if ("search".equals(permission[i])) {
                    search = "查看,";
                }
            }
            user.setManagerFlag((add + delete + download + search).replace(" ", ""));
        }

        userService.updateUser(user);
        response.getOutputStream().print("1");


    }

    /*获得当前用户头像*/
    @RequestMapping("/headPic")
    public void updatePic(Model model, HttpServletRequest request, HttpServletResponse response) throws IOException {
        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();


        Collection<? extends GrantedAuthority> authorities = userDetails.getAuthorities();
      //  System.err.println("当前GrantedAuthority的登录角色是》》》》》" + authorities);

       // request.getSession().setAttribute("role", authorities);
      //  System.err.println("sesion中的role值为》》》》》" + authorities);
        String username = userDetails.getUsername();
        //  System.out.println("当前登录用户名为" + " " + username);
        User user = userService.getUserByName(username);
        String picUrl = user.getHeadpic();
        // System.err.println("头像路径为>>>>>" + picUrl);

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/octet-stream");
        response.addHeader(
                "Content-Disposition",
                "attachment; filename=\""
                        + username
                        + "\"");

        File file = new File(picUrl);
        FileInputStream fis;
        fis = new FileInputStream(file);

        long size = file.length();
        byte[] temp = new byte[(int) size];
        fis.read(temp, 0, (int) size);
        fis.close();
        byte[] data = temp;
        response.setContentType("image/png");
        OutputStream out = response.getOutputStream();
        data = Base64.encodeBase64(data);
        out.write(data);
        out.flush();
        out.close();


    }

    /*查看权限*/
    @RequestMapping("/userInfo")
    public String viewPermission(Model model) {
        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();
        String username = userDetails.getUsername();

        User user = userService.getUserByName(username);
        String[] permission = user.getManagerFlag().split(",");

        String addstr = "无权限", deletestr = "无权限", downloadstr = "无权限", searchstr = "无权限";
        for (int i = 0; i < permission.length; i++) {
            if ("上传".equals(permission[i])) {
                addstr = "有权限";
            }
            if ("删除".equals(permission[i])) {
                deletestr = "有权限";
            }
            if ("下载".equals(permission[i])) {
                downloadstr = "有权限";
            }
            if ("查看".equals(permission[i])) {
                searchstr = "有权限";
            }

        }
        //  System.out.println(addstr + " " + deletestr + " " + updatestr + " " + searchstr);
        model.addAttribute("addstr", addstr);
        model.addAttribute("deletestr", deletestr);
        model.addAttribute("searchstr", searchstr);
        model.addAttribute("downloadstr", downloadstr);

        return "userInfo";
    }

    /*用户上传头像*/
    @RequestMapping("/uploadImg")
    public void uploadImg(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String base64 = request.getParameter("content");
        String username = request.getParameter("username");
        /*  System.out.println("后台接收到的base64数据为" + " " + username + " " + base64);*/

        if (GenerateImage(base64, username)) {
            response.getOutputStream().print("1");
        } else {
            response.getOutputStream().print("0");
        }


    }

    //base64字符串转化成图片
    public boolean GenerateImage(String imgStr, String username) throws IOException { //对字节数组字符串进行Base64解码并生成图片
        if (imgStr == null) //图像数据为空
            return false;
        BASE64Decoder decoder = new BASE64Decoder();
        System.out.println("后台接收到的base64数据为" + " " + " " + imgStr);
        String baseValue = imgStr.replaceAll(" ", "+");//前台在用Ajax传base64值的时候会把base64中的+换成空格，所以需要替换回来。
         System.out.println("后台接收到的base64数据为" + " " + " " + baseValue);
        int index = -1;

        index = baseValue.indexOf(",");//首先获取字符的位置
        String subStr = baseValue;
        if (index > 0)
            subStr = baseValue.substring(index + 1);
        //   System.out.println("后台截取数据为" + " " + " " + subStr);

        byte[] b = decoder.decodeBuffer(subStr);
        try {
            //Base64解码
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {//调整异常数据
                    b[i] += 256;
                }
            }

            String path = "D:" + File.separator + "uploadImg" + File.separator + username + ".png";
            File file = new File("D:" + File.separator + "uploadImg");
            if (!file.exists()) {//如果文件夹不存在
                file.mkdir();//创建文件夹
            }
            User user = userService.getUserByName(username);
            user.setHeadpic(path);
            userService.updateUser(user);

            System.out.println("图片存放路径为：》》》》" + path);
            //生成jpeg图片
            // String imgFilePath = "D:\\uploadImg\\new.jpg";//新生成的图片
            OutputStream out = new FileOutputStream(path);
            out.write(b);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /*验证登录用户的主题操作权限*/
    @RequestMapping(value = "/checkPermission", method = RequestMethod.GET)
    public void checkPermission(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String action = request.getParameter("action");
        System.out.println("要执行的操作为" + " " + action);

        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();
        String username = userDetails.getUsername();
        User user = userService.getUserByName(username);

        String[] permission = user.getManagerFlag().split(",");

        if (permission != null) {
            for (int i = 0; i < permission.length; i++) {
                System.out.println("当前用户的权限有》》》》" + " " + permission[i]);
                if (action.equals(permission[i])) {
                    response.getOutputStream().print("1");
                }

            }
            response.getOutputStream().print("0");
        }
        response.getOutputStream().print("0");


    }

    /*获取当前登录的角色权限*/
    @RequestMapping(value = "/checkRole", method = RequestMethod.GET)
    public void checkRole(HttpServletRequest request, HttpServletResponse response) throws IOException {

        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();
       /* Collection<? extends GrantedAuthority> authorities = userDetails.getAuthorities();
        System.err.println("当前用户的角色为》》》》"+authorities);*/

        String username = userDetails.getUsername();
         int  roleId=userService.getUserByName(username).getRole_id();
        System.err.println("当前用户的角色ID 为"+roleId);
        if (roleId==1) {
            response.getOutputStream().print("1");

        } else {
            response.getOutputStream().print("0");
        }
    }
}